package top.boycharse.blog.dao.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.boycharse.blog.dao.bean.Article;
import top.boycharse.blog.dao.repository.ArticleRepository;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class ArticleService {

    public static final int PAGE_SIZE = 20;

    @Autowired
    private ArticleRepository articleRepository;

    @Transactional
    public Article saveArticle(Article article) {
        Article temp = articleRepository.save(article);
        return temp;
    }

    public Article findArticleById(Integer id) {
        Optional<Article> article = articleRepository.findById(id);
        if (article.isPresent()) {
            return article.get();
        }else {
            return null;
        }
    }

    @Transactional
    public void deleteArticleById(Integer id) {
        articleRepository.deleteById(id);
    }

    @Transactional
    public void deleteArticle(Article article) {
        articleRepository.delete(article);
    }


    public Page<Article> getArticleWithPage(int pageIndex) {
        Pageable pageable = PageRequest.of(pageIndex, PAGE_SIZE);
        Page<Article> articles = articleRepository.findAll(pageable);
        return articles;
    }
}
